package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.mapper.*;
import com.woniu.pojo.*;
import com.woniu.mapper.LabelMapper;
import com.woniu.mapper.UserDetailMapper;
import com.woniu.mapper.UserLabelMapper;
import com.woniu.mapper.UserMapper;
import com.woniu.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.QueryUserVo;
import com.woniu.vo.UserDetailVo;
import com.woniu.vo.UserInformationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author doujiao
 * @since 2022-10-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDetailMapper userDetailMapper;
    @Resource
    private LabelMapper labelMapper;
    @Resource
    private UserLabelMapper userLabelMapper;
    @Resource
    private FamilyMapper familyMapper;
    @Resource
    private SignMapper signMapper;

    /**
     * 根据分页条件查询
     * @param currentPage
     * @param pageSize
     * @param userVo
     * @return
     */
    public PageResult queryByPage(Long currentPage, Long pageSize, QueryUserVo userVo) {
        //构建wrap
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        //分页
        IPage<User> page=new Page(currentPage,pageSize);
        PageResult pageResult = new PageResult();
        if (userVo!=null){
            //签约状态
            if (userVo.getSignStatusId()!=null && userVo.getSignStatusId()>0){
                QueryWrapper<Sign> signQueryWrapper = new QueryWrapper<>();
                signQueryWrapper.eq("status",userVo.getSignStatusId());
                List<Sign> signs = signMapper.selectList(signQueryWrapper);
                if (signs!=null){
                    for (Sign sign : signs) {
                        Long userId = sign.getUserId();
                        wrapper.eq("id",userId);
                    }
                }
            }
            if (userVo.getOrganizationId()!=null && userVo.getOrganizationId()>0){
                wrapper.eq("organization_id",userVo.getOrganizationId());
            }
            if (userVo.getTeamId()!=null && userVo.getTeamId()>0){
                wrapper.eq("team_id",userVo.getTeamId());
            }
            if (userVo.getPackageId()!=null && userVo.getPackageId()>0){
                wrapper.eq("package_id",userVo.getPackageId());
            }
            if (userVo.getLabelId()!=null){
                wrapper.eq("sign_status_id",userVo.getLabelId());
            }
            if (userVo.getName()!=null){
                wrapper.like("name",userVo.getName());
            }
            IPage<User> page1 = userMapper.selectPage(page, wrapper);
            List<User> userList = page1.getRecords();
            List<UserDetailVo> userDetailList=new ArrayList<>();
            for (User user : userList) {
                UserDetailVo userDetailVo = new UserDetailVo();
                BeanUtils.copyProperties(user,userDetailVo);
                //用户详情
                QueryWrapper<UserDetail> userDetailQueryWrapper = new QueryWrapper<>();
                userDetailQueryWrapper.eq("user_id",user.getId());
                UserDetail userDetail1 = userDetailMapper.selectOne(userDetailQueryWrapper);
                BeanUtils.copyProperties(userDetail1,userDetailVo);
                //标签
                QueryWrapper<UserLabel> wrapper1 = new QueryWrapper<>();
                wrapper.eq("user_id",user.getId());
                List<UserLabel> userLabels = userLabelMapper.selectList(wrapper1);
                List<Label> labelList=new ArrayList<>();
                for (UserLabel userLabel : userLabels) {
                    Long labelId = userLabel.getLabelId();
                    Label label = labelMapper.selectById(labelId);
                    labelList.add(label);
                }
                userDetailVo.setLabelList(labelList);
                userDetailList.add(userDetailVo);
            }
            pageResult.setTotal(page1.getTotal());
            pageResult.setData(userList);
            return pageResult;
        }
        IPage<User> page1 = userMapper.selectPage(page, null);
        List<User> userList = page1.getRecords();
        pageResult.setTotal(page1.getTotal());
        pageResult.setData(userList);
        return pageResult;
    }

    /**
     * 根据用户id查看详情
     * @param userId
     * @return
     */
    public UserDetailVo queryDetailByUserId(Long userId) {
        //
        UserDetailVo userDetailVo = new UserDetailVo();
        User user = userMapper.selectById(userId);
        BeanUtils.copyProperties(user,userDetailVo);
        //标签
        QueryWrapper<UserLabel> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<UserLabel> userLabels = userLabelMapper.selectList(wrapper);
        List<Label> labelList=new ArrayList<>();
        for (UserLabel userLabel : userLabels) {
            Long labelId = userLabel.getLabelId();
            Label label = labelMapper.selectById(labelId);
            labelList.add(label);
        }
        userDetailVo.setLabelList(labelList);
        System.err.println(labelList);
        //详情
        QueryWrapper<UserDetail> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId);
        UserDetail userDetail = userDetailMapper.selectOne(wrapper1);
        BeanUtils.copyProperties(userDetail,userDetailVo);
        //重新设置userDetail的id
        userDetailVo.setId(user.getId());
        return userDetailVo;
    }
    /**
     * 根据编辑
     */
    public Boolean edit(UserDetailVo userDetailVo) {
        User user = new User();
        UserDetail userDetail = new UserDetail();
        BeanUtils.copyProperties(userDetailVo,user);

        BeanUtils.copyProperties(userDetailVo,userDetail);
        //改变图片
        user.setImage(userDetailVo.getImage());
        int updateById = userMapper.updateById(user);
        int updateById1 = userDetailMapper.updateById(userDetail);
        if (updateById<0 && updateById1<0){
            return false;
        }
        return true;
    }

    @Override
    public Boolean removeByIdPlus(Long id) {
        userMapper.deleteById(id);
        QueryWrapper<UserDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id);
        userDetailMapper.delete(wrapper);
        return true;
    }

    /**
     * 增加
     * @param user
     * @return
     */
    public boolean add(User user) {
        int insert = userMapper.insert(user);
        Long userId = user.getId();
        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(userId);
        int insert1 = userDetailMapper.insert(userDetail);
        if (insert1<0){
            return false;
        }
        return true;
    }

    /**
     * 根据id查询服务管理的居民信息
     * @param userId
     * @return
     */
    @Override
    public UserInformationVo getPeopleById(Long userId) throws ParseException {
        UserDetailVo userDetailVo = queryDetailByUserId(userId);
        UserInformationVo userInformationVo = new UserInformationVo();
        BeanUtils.copyProperties(userDetailVo, userInformationVo);
        Date birthday = userInformationVo.getBirthday();
        SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");
        String tempDate = s1.format(birthday);
        Date bir = s2.parse(tempDate);
        Calendar calNow = Calendar.getInstance();
        Calendar calBir = Calendar.getInstance();
        calBir.setTime(bir);
        int yearNow = calNow.get(Calendar.YEAR);
        int monthNow = calNow.get(Calendar.MONTH);
        int dayNow = calNow.get(Calendar.DAY_OF_MONTH);
        int yearBir = calBir.get(Calendar.YEAR);
        int monthBir = calBir.get(Calendar.MONTH);
        int dayBir = calBir.get(Calendar.DAY_OF_MONTH);
        int ago = yearNow - yearBir;
        if(monthNow < monthBir || (monthNow == monthNow && dayNow < dayBir)){
            ago--;
        }
        userInformationVo.setAgo(ago);
        QueryWrapper<Family> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Family> familyList = familyMapper.selectList(wrapper);
        userInformationVo.setFamilyList(familyList);
        return userInformationVo;
    }


    /**
     * 修改用户发布状态
     * @param userId
     * @return
     */
    @Override
    public boolean saveStatus(Long userId) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        User user = userMapper.selectById(userId);
        if(!StringUtils.isEmpty(user.getStatus()) && user.getStatus().equals("0")){
            updateWrapper.set("status", "1");
            updateWrapper.eq("id", userId);
            return update(updateWrapper);
        }
        if(!StringUtils.isEmpty(user.getStatus()) && user.getStatus().equals("1")){
            updateWrapper.set("status", "0");
            updateWrapper.eq("id", userId);
            return update(updateWrapper);
        }
        return false;
    }
}
